"""
定时上报任务调度器
"""
import threading
import time
import logging
from typing import List, Dict
from com.db.scan_account_manager import ScanAccountManager
from reqapi.track_report import TrackReportApi

logger = logging.getLogger(__name__)

class TrackReportScheduler:
    """定时上报调度器"""
    
    def __init__(self):
        self.running = False
        self.thread = None
        self.scan_account_manager = ScanAccountManager()
        
    def start(self):
        """启动定时上报"""
        if self.running:
            logger.warning("定时上报任务已经在运行中")
            return
            
        self.running = True
        self.thread = threading.Thread(target=self._run, daemon=True)
        self.thread.start()
        logger.info("定时上报任务已启动")
        
    def stop(self):
        """停止定时上报"""
        self.running = False
        if self.thread:
            self.thread.join()
            self.thread = None
        logger.info("定时上报任务已停止")
        
    def _run(self):
        """运行定时上报任务"""
        while self.running:
            try:
                # 获取有效的扫货账号列表
                accounts = self.scan_account_manager.get_active_accounts()
                if not accounts:
                    logger.warning("没有找到有效的扫货账号")
                    time.sleep(60)  # 如果没有账号，等待1分钟后重试
                    continue
                
                # 遍历每个账号进行上报
                for account in accounts:
                    if not self.running:
                        break
                        
                    try:
                        # 创建上报API实例
                        api = TrackReportApi(
                            device_id=account['device_id'],
                            auth_token=account['uu_token'],
                            uk=account['uk']
                        )
                        
                        # 执行上报
                        success = api.report(str(account['uu_user_id']))
                        if success:
                            logger.info(f"账号 {account['uu_user_id']} 上报成功")
                        else:
                            logger.error(f"账号 {account['uu_user_id']} 上报失败")
                            
                    except Exception as e:
                        logger.error(f"账号 {account['uu_user_id']} 上报出错: {str(e)}")
                        
                    # 等待1分钟
                    if self.running:
                        time.sleep(60)
                        
            except Exception as e:
                logger.error(f"定时上报任务出错: {str(e)}")
                if self.running:
                    time.sleep(60)  # 发生错误时等待1分钟后重试
